import logging
from pathlib import Path
from datetime import datetime, timedelta
import hashlib
import hmac

class DataCleaner:
    def __init__(self, data_dir='/var/app/data', secret_key=None):
        self.data_dir = Path(data_dir)
        self.secret_key = secret_key.encode() if secret_key else None
        self.logger = logging.getLogger(__name__)

    def _validate_path(self, path):
        """确保路径在允许的目录内"""
        try:
            return path.resolve().relative_to(self.data_dir.resolve())
        except ValueError:
            raise PermissionError(f"Access to {path} denied")

    def _generate_audit_log(self, operation, path, success=True, error=None):
        """生成HMAC签名的审计日志"""
        log_entry = {
            'timestamp': datetime.utcnow().isoformat(),
            'operation': operation,
            'path': str(path),
            'success': success,
            'error': str(error) if error else None
        }
        
        if self.secret_key:
            signature = hmac.new(
                self.secret_key,
                msg=str(log_entry).encode(),
                digestmod=hashlib.sha256
            ).hexdigest()
            log_entry['signature'] = signature
        
        return log_entry

    def safe_remove(self, path_patterns, retention_days=30):
        """安全删除符合模式的文件"""
        active_sessions = self._get_active_sessions()
        cleaned_files = []
        
        for pattern in path_patterns:
            for path in self.data_dir.glob(pattern):
                try:
                    self._validate_path(path)
                    
                    if path.is_dir():
                        self.logger.warning(f"Skipping directory {path}")
                        continue
                        
                    if path.name in active_sessions:
                        self.logger.info(f"Preserving active session file {path}")
                        continue
                        
                    if datetime.fromtimestamp(path.stat().st_mtime) > datetime.now() - timedelta(days=retention_days):
                        self.logger.info(f"File {path} within retention period")
                        continue
                        
                    path.unlink()
                    cleaned_files.append(self._generate_audit_log('delete', path))
                    
                except Exception as e:
                    self.logger.error(f"Failed to delete {path}: {str(e)}")
                    cleaned_files.append(self._generate_audit_log('delete', path, False, e))
                    
        return cleaned_files

    def _get_active_sessions(self):
        """获取活动会话文件列表（实现应连接到会话管理系统）"""
        # 示例实现：扫描lock文件
        return [f.name for f in self.data_dir.glob('*.lock')]

if __name__ == '__main__':
    # 示例用法
    cleaner = DataCleaner(secret_key='your-secret-key')
    results = cleaner.safe_remove(['*.log', '*.tmp', 'test_*'])
    print(f"Cleaned {len(results)} files")